package com.zc.controller.oldStore;

import com.zc.dto.AdPictureURL;
import com.zc.dto.ResultDto;
import com.zc.entity.Image;
import com.zc.entity.ImgInfo;
import com.zc.service.JedisClient;
import com.zc.service.lightbox.LightboxServer;
import com.zc.service.picture.PhotoUploadService;
import com.zc.utils.Contants;
import com.zc.utils.CreateYZM;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("/photo")
public class PhotoUploadController extends BaseController {
    @Resource
    private PhotoUploadService biz;
    @Resource
    private LightboxServer lightBiz;

    @Resource
    private JedisClient jedis;

    @RequestMapping("/preUpload")
    public String preUpload() {
        return "photoUpload";
    }

    /**
     * 图片上传
     *
     * @param request 图片流
     * @return
     */
    @RequestMapping("/upload")
    public String upload(MultipartHttpServletRequest request) {
        MultipartFile photo = request.getFile("photo");
        String fileName = UUID.randomUUID().toString();
        String path = Contants.IMAGE_PATH + fileName;
        File newFile = new File(path);
        try {
            photo.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Image image = new Image();
        image.setPicUrl("picture/" + fileName);
        image.setState(1);
        try {
            biz.save(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/lightbox/findAll?state=1";
    }

    /**
     * 展示图片拖拽功能的页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/jiuGongTu")
    public String jiuGongTuShow(Model model) {
        List<Image> list = lightBiz.findAll(1);
        model.addAttribute("list", list);
        return "picPosition";
    }

    /**
     * 点击修改图片
     *
     * @param id
     * @param request
     */
    @ResponseBody
    @RequestMapping("/updateById")
    public String updateById(int id, MultipartHttpServletRequest request) {
        try {
            Image img = new Image();
            MultipartFile photo = request.getFile("photo");
            String fileNa = UUID.randomUUID().toString();
            String path = Contants.iINDEX_IMAGE_PATH + fileNa;
            File newFile = new File(path);
            try {
                photo.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            img.setId(id);
            img.setPicUrl("picture/imggif/" + fileNa);
            img.setState(1);
            biz.updatePicture(img);
        } catch (Exception e) {
        }
        return "11";
    }

    /**
     * 修改图片顺序
     *
     * @param rank
     */
    @ResponseBody
    @RequestMapping("/updateRank")
    public String updateRank(String rank) {
        try {
            biz.updateRank(rank);
        } catch (Exception e) {
            /* e.printStackTrace();*/
        }
        return "SXZZ";
    }

    /**
     * wangEditor编辑页面跳转
     */
    @RequestMapping("/wangEditor")
    public String wangEditor() {
        return "wangEditor";
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/wangEditorUpload")
    public AdPictureURL upload(@RequestParam("photo") List<MultipartFile> list) {
        Integer errno = 0;
        List<String> urls = new ArrayList<>();
        AdPictureURL returnAd = new AdPictureURL();
        Map<String, Object> map = new HashMap();
        List<String> adlist = new ArrayList<>();
        if (list.size() == 0) {
            errno = 1;
        }
        //ImgInfo 将图片存放工程目录的地址存到数据库的操作
        ImgInfo img = new ImgInfo();
        for (MultipartFile file : list) {
            String realName = "";
            if (file != null) {
                String fileName = UUID.randomUUID().toString();
                String path = Contants.IMAGE_PATH + fileName;
                File newFile = new File(Contants.IMAGE_PATH + fileName);
                try {
                    file.transferTo(newFile);
                    String databaseUrl = "http://192.168.1.58:8081/study/picture/" + fileName;
                    urls.add(databaseUrl);
                } catch (IOException e) {
                    errno = 1;
                    e.printStackTrace();
                }
            }
        }
        biz.saveImg(urls);
        returnAd.setData(urls);
        returnAd.setErrno(errno);
        return returnAd;
    }

    /**
     * 验证码图片跳转
     */
    @RequestMapping("/preYZM")
    public String preYZM(Model model) {
//        String identification = UUIDimpl.toUUID();
//        model.addAttribute("identification",identification);
        return "createYZM";
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/CreateYZM", method = RequestMethod.GET)
    public void CreateYZM(HttpServletResponse response, HttpServletRequest request, String identification) {
        response.setContentType("blob");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        CreateYZM vCode = new CreateYZM(120, 40, 4, 100);
        //将生成的验证码和标识符,放到redis,做验证
        jedis.set(identification, vCode.getCode());
        //设置时效性(3分钟)
        //jedis.expire(identification,3);
        jedis.expire(identification, 3 * 60);
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            LOG.error("CreateYZM error ::,{}",e);
        }
    }

    /**
     * 验证验证码
     */
    @ResponseBody
    @RequestMapping("/confirmYZM")
    public ResultDto confirmYZM(String identification, String code) {
        ResultDto result = new ResultDto();
        if (code != null && (!"".equals(code))) {
            String jedisString = jedis.get(identification);
            if (jedisString != null) {
                if (jedisString.equalsIgnoreCase(code)) {
                    result.setSuccess(true);
                    result.setMessage("验证成功");
                } else {
                    result.setSuccess(
                            false
                    );
                    result.setMessage("输入的验证码不匹配");
                }
            } else {
                result.setSuccess(
                        false
                );
                result.setMessage("验证码已失效,请更换验证码");
            }
        } else {

            result.setSuccess(
                    false
            );
            result.setMessage("输入了空验证码");

        }

        return result;
    }
}
